package com.cn.redis;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import com.cn.common.utils.ApplicationContextHolder;
import com.cn.common.utils.LoggerUtils;

public class RedisCache implements Cache {

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final String id; // cache instance id

	private RedisTemplate<Serializable,Serializable> redisTemplate;

    private static final long EXPIRE_TIME_IN_MINUTES = 30; // redis过期时间

    public RedisCache(String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
    }

    /**
     * mybatis缓存操作对象的标识符。一个mapper对应一个mybatis的缓存操作对象
     */
    @Override
    public String getId() {
        return id;
    }

    /**
     * Put query result to redis
     * 将查询结果塞入缓存
     * @param key
     * @param value
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
    public void putObject(Object key, Object value) {
        RedisTemplate redisTemplate = getRedisTemplate();
        ValueOperations opsForValue = redisTemplate.opsForValue();
        opsForValue.set(key, value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
        LoggerUtils.debug(getClass(), "Put query result to redis");
    }

    /**
     * Get cached query result from redis
     * 从缓存中获取被缓存的查询结果
     * @param key
     * @return
     */
    @SuppressWarnings("rawtypes")
	@Override
    public Object getObject(Object key) {
        RedisTemplate redisTemplate = getRedisTemplate();
        ValueOperations opsForValue = redisTemplate.opsForValue();
        LoggerUtils.debug(getClass(),"Get cached query result from redis");
        return opsForValue.get(key);
    }

    /**
     * Remove cached query result from redis
     * 从缓存中删除对应的key、value。只有在回滚时触发。
     * 一般我们也可以不用实现，具体使用方式请参考：
     * org.apache.ibatis.cache.decorators.TransactionalCache
     *
     * @param key
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
    public Object removeObject(Object key) {
        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.delete(key);
        LoggerUtils.debug(getClass(),"Remove cached query result from redis");
        return null;
    }

    /**
     * Clears this cache instance
     * 发生更新时，清除缓存
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
    public void clear() {
        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.execute((RedisCallback) connection -> {
            connection.flushDb();
            return null;
        });
        LoggerUtils.debug(getClass(),"Clear all the cached query result from redis");
    }

    /**
     * This method is not used
     * 可选实现。返回缓存的数量
     * @return
     */
    @Override
    public int getSize() {
        return 0;
    }

    /**
     * 可选实现。用于实现原子性的缓存操作
     */
    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    @SuppressWarnings("rawtypes")
	private RedisTemplate getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
        }
        return redisTemplate;
    }
}
